package com.example.demo.task;



import com.example.demo.entity.Dakamingxi;
import com.example.demo.service.BaseService;
import com.example.demo.service.DakamingxiService;
import com.example.demo.util.DateUtil;
import com.example.demo.util.RedisUtil;
import com.example.demo.util.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

import static com.example.demo.util.DateUtil.date2TimeStamp;


@Service
public class DaKaServiceTaskl implements BaseService {
    @Autowired
    RestTemplate restTemplate;
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    DakamingxiService dakamingxiService;

    public List<Dakamingxi> getLogList(String timeStamp) throws ParseException {
        String startTimeStamp = redisUtil.get("timeStamp").toString();
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date=  new Date(simpleDateFormat.parse(DateUtil.timeStamp2Date(startTimeStamp,"yyyy-MM-dd HH:mm:ss")).getTime()-1200000);
        startTimeStamp=DateUtil.dateToStrLong(date);
        startTimeStamp=date2TimeStamp(startTimeStamp,"yyyy-MM-dd HH:mm:ss");
        HttpHeaders requestHeaders = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        requestHeaders.setContentType(type);
        requestHeaders.add("Accept", MediaType.APPLICATION_JSON.toString());
        //获取token
        String token = getToken(USERNAME, PASSWORD, requestHeaders);
        //获取站点
        requestHeaders.add("X-AUTH-TOKEN", token);
        List<Map> sites = getSites(requestHeaders);

        if (StringUtils.isEmpty(sites)) {
            return Collections.emptyList();
        }
        //查询站点下用户登录日志
        for (Map site : sites) {
            try {
                getLogList(startTimeStamp, timeStamp, site.get("id").toString(),site.get("sitename").toString(), requestHeaders);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        redisUtil.set("timeStamp", timeStamp);
        return null;
    }

    private String getToken(String username, String password, HttpHeaders requestHeaders) {


        Map map = new HashMap();
        map.put("userName", username);
        map.put("password", password);
        HttpEntity<Map> requestEntity = new HttpEntity<Map>(map, requestHeaders);
        ResponseEntity<String> response = restTemplate.postForEntity(TOKEN_URL, requestEntity, String.class);
        JSONObject jsonResponse = new JSONObject(response.getBody());
        JSONObject jsonObject = jsonResponse.getJSONObject("data");
        return jsonObject.get("token_id").toString();
    }

    private List<Map> getSites(HttpHeaders requestHeaders) {
        HttpEntity<String> requestEntity = new HttpEntity<>(requestHeaders);
        ResponseEntity<String> response = restTemplate.exchange(SITE_URL, HttpMethod.GET, requestEntity, String.class);

        JSONObject jsonResponse = new JSONObject(response.getBody());
        JSONArray jsonObject = jsonResponse.getJSONArray("data");
        List list = new ArrayList();
        for (int i = 0; i < jsonObject.length(); i++) {
            Map map=new HashMap();
            String id = jsonObject.getJSONObject(i).getString("id");
            String sitename = jsonObject.getJSONObject(i).getString("name");
            map.put("id",id);
            map.put("sitename",sitename);
            list.add(map);
        }
        return list;
    }

    private List<Dakamingxi> getLogList(String startTimeStamp, String timeStamp, String site, String sitename,HttpHeaders requestHeaders) throws ParseException {
        System.out.println("站点："+site);
        List<Dakamingxi> dtoList = new ArrayList<>();
        List<Dakamingxi> dtoList1 = new ArrayList<>();
        LocalDate localDate = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");//获得当前日期
        HttpEntity<String> requestEntity = new HttpEntity<>(requestHeaders);
        List<Dakamingxi> dakamingxiList3 = new ArrayList<>();
        //站点下所有的登录信息
        Boolean flag = true;
        String nextRowkey = "";
        String startRowkey = "";
        String url = "";
        List<Dakamingxi> list = new ArrayList<>();

        while (flag) {
            url = LOGURL + "pageSize=200&siteId=" + site
                    + "&beginTime=" + startTimeStamp + "&endTime=" + timeStamp + "&sceneName=1&startQueryRowKey=" + startRowkey;
            ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class);
            JSONObject jsonResponses = new JSONObject(response.getBody());
            JSONObject jsonArrays = (JSONObject) jsonResponses.get("data");
            JSONArray jsonArray1 = jsonArrays.getJSONArray("deviceLog");
            nextRowkey=jsonArrays.getString("nextRowkey");
            for (int j = 0; j < jsonArray1.length(); j++) {
                String detail = jsonArray1.getJSONObject(j).get("detail").toString();
                if (detail.contains("[WLAN_STA_INFO_AP_ASSOCIATE]")) {
                    Dakamingxi dakamingxis = new Dakamingxi();
                    // 该信息包含 则为一个新的对象 并放入集合中
                    dakamingxis.setSiteid(site);
                    dakamingxis.setSitename(sitename);
                    dakamingxis.setMac(jsonArray1.getJSONObject(j).get("stationMac").toString());
                    dakamingxis.setFirsttime(jsonArray1.getJSONObject(j).get("time").toString());
                    dakamingxis.setSwtime(jsonArray1.getJSONObject(j).get("time").toString());
                    dakamingxis.setAccount(jsonArray1.getJSONObject(j).get("stationMac").toString().trim().replace("-", ""));
                    //dakamingxis.setDate(sf.parse(localDate.format(formatter)));
                    dakamingxis.setDate(sf.parse(dakamingxis.getFirsttime()));
                    list.add(dakamingxis);
                }else if (detail.contains("WLAN_LOG_STA_ONLINEFAIL_OR_OFFLINE_INFO")) {
                    Dakamingxi dakamingxis = new Dakamingxi();
                    // 该信息包含 则为一个新的对象 并放入集合中
                    dakamingxis.setSiteid(site);
                    dakamingxis.setSitename(sitename);
                    dakamingxis.setMac(jsonArray1.getJSONObject(j).get("stationMac").toString());
                    dakamingxis.setEwtime(jsonArray1.getJSONObject(j).get("time").toString());
                    dakamingxis.setEndtime(jsonArray1.getJSONObject(j).get("time").toString());
                    dakamingxis.setAccount(jsonArray1.getJSONObject(j).get("stationMac").toString().trim().replace("-", ""));
                    dakamingxis.setDate(sf.parse(dakamingxis.getEndtime()));
                    dakamingxiList3.add(dakamingxis);
                }
            }
            if (!nextRowkey.equals("")) {
                //下次访问的起始索引
                startRowkey = nextRowkey;
            } else {
                //跳出循环
                break;
            }
        }
        //新增打卡统计数据
        Map<String, List<Dakamingxi>> collect1 = dakamingxiList3.stream().collect(Collectors.groupingBy(Dakamingxi::getMac));//根据mac分组
        //内部遍历 比较，获取最早的打卡时间
        collect1.entrySet().forEach(entry ->
        {
            List<Dakamingxi> dakamingxiList = entry.getValue();
            Optional<Dakamingxi> dakamingxi = dakamingxiList.stream()
                    .sorted(Comparator.comparing(Dakamingxi::getEndtime).reversed())
                    .collect(Collectors.toList()).stream().findFirst();
            dtoList1.add(dakamingxi.get()); //放入集合中
        });
        Map<String, List<Dakamingxi>> collect = list.stream().collect(Collectors.groupingBy(Dakamingxi::getMac));//根据mac分组
        //内部遍历 比较，获取最早的打卡时间
        collect.entrySet().forEach(entry ->
        {
            List<Dakamingxi> dakamingxiList = entry.getValue();
            Optional<Dakamingxi> dakamingxi = dakamingxiList.stream()
                    .sorted(Comparator.comparing(Dakamingxi::getFirsttime))
                    .collect(Collectors.toList()).stream().findFirst();
            dtoList.add(dakamingxi.get()); //放入集合中
        });
        dakamingxiService.insertDakmingxi(dtoList);
        dakamingxiService.updateDakmingxi(dtoList1);
        return dtoList;
    }
}
